	String.prototype.trim = function() { 
	  return this.replace(/(^\s*)|(\s*$)/g, ''); 
	};

  var treeObj;  //ztree 对象
  var treeNodeData;

  var topChannelData = {};  //顶级渠道对象
  function refreshTree(channelCode, defChannelCode) {
    if (channelCode == '') {
      layer.msg("请选择渠道!");
      return;
    }
    var rootData = topChannelData[channelCode];

    var parentCodes = rootData.channelCode;
    if (rootData.parentCodes) {
      parentCodes = rootData.parentCodes + "," + parentCodes;
    }

    $X('/boss/channelService', 'listChildrenChannelByTopCode').callx({
    	topChannelCode : parentCodes,
      onResult: function (data) {
        if(data && data.length > 0) {
          var tree = JSON.stringify(data);
          tree = jQuery.parseJSON(tree);
          //tree.push(topChannelData[channelCode]);
          initTree(tree);
          if(defChannelCode) {
            var node = treeObj.getNodeByParam("channelCode", defChannelCode);
            treeObj.selectNode(node,false);
            treeObj.expandNode(node, true);
          }
        }
      },
      onError: function (error) {
        onError(error);
      }
    });
  }

  function initTree(tree) {
    //配置树的属性
    var setting = {
      data: {
        simpleData: {
          enable: true,
          idKey: "channelCode",
          pIdKey: "parentCode"
        },
        key: {
          name: "name"
        }
      },
      callback: {
        onClick: zTreeOnclick
      },
      view: {
        fontCss: getFontCss
      }
    }
    //创建自定义树
    treeObj = $.fn.zTree.init($("#treeDemo"), setting, tree);
  }

  //点击事件
  function zTreeOnclick(event, treeId, treeNode) {

    treeNodeData = treeNode;
    $("#addNextChannelBtn").show();
    $("#importChildChannelBtn").show();

//      addOrUpdateData.defaultPriceType = topChannelData[addOrUpdateData.topChannelCode].defaultPriceType;
//      addOrUpdateData.chequesType=topChannelData[addOrUpdateData.topChannelCode].chequesType;
//      addOrUpdateData.distributionType=topChannelData[addOrUpdateData.topChannelCode].distributionType;
//      addOrUpdateData.channelType=topChannelData[addOrUpdateData.topChannelCode].channelType;
    var selectNode = {
        channelCode:treeNode.channelCode,
        channelName:treeNode.name,
        chequesType:treeNode.channelPayeeType,
        isCheckStock:treeNode.isCheckStock,
        distributionType:treeNode.distributionType,
        channelType:treeNode.channelType,
        id:treeNode.id
        
    }
    $("#addOrUpdateForm input[name='selectChannelInfo']").val(JSON.stringify(selectNode));
    var parentNode = treeNode.getParentNode();
    if (parentNode) {
      treeNode.parentChannelName = parentNode.name;
    }
    treeNode.operationType = 1;
    //treeNode.warehouseCode = '';
    var treeType=0; //0:顶级 1:目录 2:叶子无仓库 3:叶子有仓库
    var hasParent=false; //有无父级
    var hasLeaf=false; //有无子级
    var isStore=false;
    if (treeNode.getParentNode()){
    	hasParent = true;
    }
    if (treeNode.hasLeaf && (treeNode.hasLeaf === '1' || treeNode.hasLeaf===1)){
    	hasLeaf = true;
    }
    if (treeNode.warehouseCode){
    	isStore = true;
    }
    if (hasParent){
        if (hasLeaf){
            treeType=3; //目录
        }else{
          if (!isStore){
              treeType=3; //叶子无仓库
          }else{
              treeType=3; //叶子 含有仓库
          }
        }
    }
    treeNode.treeType=treeType;

    if (!treeNode.getParentNode()) {
      treeNode.isTop = 1;
      treeNode.topChannelCode = '';
    } else {
      var topChannelCode = $("#channelSelect").val();
      treeNode.topChannelCode = topChannelCode;
    }


    if (treeType === 3) { //最小节点 有仓库
      //查询该渠道的仓库信息
      $X("/boss/channelService", "getChannelRegionByChannelCode").callx({
    	  topChannelCode : treeNode.topChannelCode,
        channelCode: treeNode.channelCode,
        onResult: function (result) {
            if (result) {
                //treeNode.warehouseCode = result[0].warehouseCode;
                //treeNode.warehouseName=result[0].warehouseName;
                //treeNode.stocksProportion=result[0].stocksProportion;
            	treeNode.regionCode = result.regionCode;
            }
//          showChannelDetail(treeNodeData);
            showChannelDetail(treeNode);
        },
        onError: function (error) {
          onError(error);
          layer.msg("获取数据失败");
        }
      });
    } else {
      showChannelDetail(treeNodeData);
    }
    layer.closeAll('loading');
  }

  function  ajaxConfig(treeNode) {
      $X("/channel/channelManagerService", "queryChannelConfigByChannelCode").callx({
          channelCode: treeNode.channelCode,
          onResult: function (result) {
              if (result) {
                  treeNode['channelConfigStr']=JSON.stringify(result);
                for (var i=0,j=result.length;i<j;i++){
                    var serverConf=result[i];
                    treeNode['server'+serverConf.serviceType]=serverConf;
                }
              }
              showChannelDetail(treeNode);
          },
          onError: function (error) {
              onError(error);
              layer.msg("获取数据失败");
          }
      });
  }

  function saveChannel(type) {
    var data = treeNodeData || {}; //原始值
      var channelConfigStr = $("#addOrUpdateForm input[name='channelConfigStr']").val();
      if (channelConfigStr.length>0){
          var channelConfig=JSON.parse(channelConfigStr);
          data.channelServerList=channelConfig;
      }
    var channelServerList=[];
    var addOrUpdateData = $.openx.getJsonObj("addOrUpdateForm");
    if (addOrUpdateData.serviceType0){
          channelServerList.push({serviceType:0})
      }
      if (addOrUpdateData.serviceType1){
          channelServerList.push({serviceType:1,cashOnDelivery:addOrUpdateData.cashOnDelivery1,customerPickUp:addOrUpdateData.customerPickUp1})
      }

      if (addOrUpdateData.serviceType2){
          var areaCode = getSelectedCode("province")||'0';
          //addData.areaCode = areaCode;
          channelServerList.push({serviceType:2,cashOnDelivery:addOrUpdateData.cashOnDelivery2,areaList:[areaCode]})
      }

      addOrUpdateData.channelServerList=channelServerList;
      addOrUpdateData.treeType=data.treeType;

    if (type === '0') {  //新增
     // var addData = $("#addOrUpdateForm").serializeObject();
        //校验
        if (!validateForm(addOrUpdateData)) {
            return false;
        }

      var isTop = 0;
      if (addOrUpdateData.topChannelCode) {
          addOrUpdateData.channelCode = addOrUpdateData.topChannelCode + "_" + addOrUpdateData.channelCode;
      } else {
        isTop = 1;
      }
      var warehouseCode = $("#addOrUpdateForm input[name='warehouseCode']").val();
      if (warehouseCode) {
          addOrUpdateData.warehouseCode = warehouseCode;
      }
      if (addOrUpdateData.parentCode && addOrUpdateData.topChannelCode && addOrUpdateData.defaultPriceType == undefined) {
        /*if (topChannelData[addOrUpdateData.topChannelCode]) {
            addOrUpdateData.defaultPriceType = topChannelData[addOrUpdateData.topChannelCode].defaultPriceType;
            addOrUpdateData.chequesType=topChannelData[addOrUpdateData.topChannelCode].chequesType;
            addOrUpdateData.distributionType=topChannelData[addOrUpdateData.topChannelCode].distributionType;
            addOrUpdateData.channelType=topChannelData[addOrUpdateData.topChannelCode].channelType;
        }*/
        addOrUpdateData.cashOnDelivery = addOrUpdateData.cashOnDelivery1;
        addOrUpdateData.customerPickUp = addOrUpdateData.customerPickUp1;
        var regionCode = addOrUpdateData.district ? addOrUpdateData.district : addOrUpdateData.city;
          regionCode = regionCode ? regionCode : addOrUpdateData.province;
        if(regionCode) {
	        var region = {};
	        region.topChannelCode = addOrUpdateData.topChannelCode;
	        region.channelCode = addOrUpdateData.channelCode;
	        region.regionCode = regionCode;
	        addOrUpdateData.channelRegion = region;
        }
      }

      if($("#remark2").val() && $("#remark2").val().length > 200) {
        layer.msg('渠道说明不能超过100个中文字符');
        return ;
      }

      addOrUpdateData.remark = $("#remark2").val();
      

      $X("/boss/channelService", "addChannel").callx({
    	  channel: addOrUpdateData,
        onResult: function (result) {
          result.isTop = isTop;
          refreshAfterAdd(treeNodeData, result);
          layer.msg("新增成功");
        },
        onError: function (error) {
          error = JSON.parse(error)
          layer.msg(error.message || "添加失败,请检查渠道编码是否重复");
        }
      });

    } else if (type === '1') { //修改
//      var updateData = $("#addOrUpdateForm").serializeObject();


      if (!validateForm(addOrUpdateData)) {
        return false;
      }

      var oldwarehouseCode = $("#addOrUpdateForm input[name='warehouseCode']").attr("data-oldwarehouse");
      var newwarehouseCode = addOrUpdateData.warehouseCode;

      var id = data.id;

      var topChannelCode = addOrUpdateData.topChannelCode || addOrUpdateData.channelCode;

        var updateData = getUpdateData(addOrUpdateData, data) || {};


        //if (warehouseCode && newwarehouseCode){
            updateData.warehouseCode = newwarehouseCode;
//            updateData.warehouseCode = oldwarehouseCode;
        //}
        updateData.channelCode = data.channelCode;
        updateData.id = id;
        updateData.isCheckStock = addOrUpdateData.isCheckStock;
        updateData.isGivePoint = addOrUpdateData.isGivePoint;
        updateData.isRebateRefund = addOrUpdateData.isRebateRefund;

        //是否支持管制药
        console.log("zzzzzzzzzzzzzzzzzzzzzzzzzzzz"+JSON.stringify(addOrUpdateData))
        updateData.allowMangeGoods = addOrUpdateData.allowMangeGoods;

        //updateData.treeType=data.treeType;

        var channelServerList=updateData.channelServerList;
        var newChannelServerList=[];
        if (channelServerList && channelServerList.length>0){
            for (var i=0,j=channelServerList.length;i<j;i++){
                var item=channelServerList[i];
                if(item.serviceType==='2'){  //B2C 填充经纬度
                    var area=[];
                    var areaCode = getSelectedCode("province")||'0';
                    area.push(areaCode);
                    item.areaList=area;
                }
                newChannelServerList.push(item);
            }
        }
        if (newChannelServerList){
          updateData.channelServerList=newChannelServerList;
        }

        if(data.treeType===2 || data.treeType ===3){
          updateData.serviceMode = $("#addOrUpdateForm input[name='serviceMode']:checked").val();
        }

        if($("#remark2").val() && $("#remark2").val().length > 200) {
          layer.msg('渠道说明不能超过100个中文字符');
          return ;
        }

        updateData.remark = $("#remark2").val();

      
      if (addOrUpdateData != null) {
        $X("/boss/channelService", "updateChannel").callx({
        	channel: updateData,
          onResult: function (result) {
            layer.msg("修改成功");
            if (data.hasLeaf != '1') {  
            	updateTreeNode(treeNodeData, updateData);
            } 
	        var selectCode = $("#channelSelect").val();
	          //调用类目接口展示
	        refreshTree(selectCode, data.channelCode);
            
            if (updateData && (updateData.channelType || updateData.channelStatus || updateData.chequesType || updateData.distributionType || updateData.defaultPriceType || updateData.channelDesc || updateData.isCheckStock )) {
              var firstdata = topChannelData[topChannelCode];
              if (updateData.longitude){
                  firstdata.longitude = updateData.longitude;
                  treeNodeData.longitude = updateData.longitude;
              }
              if (updateData.latitude){
                  firstdata.latitude = updateData.latitude;
                  treeNodeData.latitude = updateData.latitude;
              }
              if (updateData.defaultPriceType){
                  firstdata.defaultPriceType = parseInt(updateData.defaultPriceType);
                  treeNodeData.defaultPriceType = parseInt(updateData.defaultPriceType);
              }
              if (updateData.channelType){
                 firstdata.channelType =  parseInt(updateData.channelType);
                  treeNodeData.channelType =  parseInt(updateData.channelType);
              }
              
              if (updateData.isCheckStock){
                  firstdata.isCheckStock =  parseInt(updateData.isCheckStock);
                   treeNodeData.isCheckStock =  parseInt(updateData.isCheckStock);
               }
              if (updateData.channelStatus){
                  if (data.treeType===0){
                      firstdata.channelStatus =  parseInt(updateData.channelStatus);
                  }
                  treeNodeData.channelStatus =  updateData.channelStatus;
              }
              if (updateData.chequesType){
                  firstdata.chequesType =  parseInt(updateData.chequesType);
                  treeNodeData.chequesType =  parseInt(updateData.chequesType);
              }
              if (updateData.distributionType){
                  firstdata.distributionType = parseInt(updateData.distributionType);
                  treeNodeData.distributionType = parseInt(updateData.distributionType);
              }
              if (updateData.channelDesc){
                  firstdata.channelDesc = updateData.channelDesc;
                  treeNodeData.channelDesc = updateData.channelDesc;
              }
              topChannelData[topChannelCode] = firstdata;
            }
                treeNodeData.warehouseCode=updateData.warehouseCode;
                treeNodeData.whetherStore=1; //有效叶子了
              if (updateData.priceSource){
                  treeNodeData.priceSource=updateData.priceSource;
              }
              if (updateData.serviceTime){
                  treeNodeData.serviceTime=updateData.serviceTime;
              }
              if (updateData.hasGoods){
                  treeNodeData.hasGoods=updateData.hasGoods;
              }
              treeNodeData.regionCode=updateData.channelRegion.regionCode;

              treeObj.updateNode(treeNodeData);
            if (updateData.newWarehouseCode){
               $("#addOrUpdateForm input[name='warehouseCode']").attr("data-oldwarehouse",updateData.newWarehouseCode);
            }
          },
          onError: function (error) {
            error = JSON.parse(error)
            layer.msg(error.message || "修改失败")
          }

        });
      } else {
        layer.msg("修改成功");
       
      }
    }
  }

  function refreshAfterAdd(treeNode, resultData) {
    topChannelData[resultData.channelCode] = resultData;
    if (resultData.parentCode && resultData.parentCode != '') {  //新增下一级
      var nodes = new Array();
      nodes.push(resultData);
//            treeObj.expandAll(false);  //折叠所有
      //新增node
      treeObj.addNodes(treeNode, resultData);
      treeObj.expandNode(treeNode, true, true, true);

    } else {
      refreshTopChannel(function () {  //新增顶级
        topChannelData[resultData.channelCode] = resultData;
//                $("#channelSelect").val(resultData.id);
        $("#channelSelect").val(resultData.channelCode).trigger("change");
        //调用类目接口展示
        var newData = new Array();
        newData.push(resultData);
        initTree(newData); //创建树
        //showChannelDetail(resultData); //刷新右边内容
        //$("#addNextChannelBtn").hide();
        //$("#importChildChannelBtn").hide();
      });
    }
  }

  function showChannelDetail(data) {
    var areaData = queryAreaDetailByAreaCode(data.regionCode);

    var innerHTML = $("#addOrUpdateChannelTemplate").html();
    laytpl(innerHTML).render(data, function (html) {
      $("#channelDetailDiv").html(html);
      $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",});
       initAreaSelect("province", "city", "district");

       /*if(data.treeType === 3){
          $(".autoClass").removeClass("hidden");
          if (data.server1 && data.server1.delFlag===0){
              $("#serviceType1Div").removeClass("hidden");
          }
          if (data.server2 && data.server2.delFlag===0){
              $("#serviceType2Div").removeClass("hidden");
          }
      }

       $('input:checkbox').on('ifChecked', function(event){ //ifCreated 事件应该在插件初始化之前绑定
            var name;
            if (event && event.currentTarget){
                name=event.currentTarget.name;
            }
            if (name){
                var $div=$("#"+name+"Div");
                if ($div){
                    $div.removeClass("hidden");
                }
            }
        });

        $('input:checkbox').on('ifUnchecked', function(event){
            var name;
            if (event && event.currentTarget){
                name=event.currentTarget.name;
            }
            if (name){
                var $div=$("#"+name+"Div");
                if ($div){
                    $div.removeClass("hidden").addClass("hidden");
                }
            }
        });*/


      var areaCode=null;
      if (data.server2 && data.server2.areaList){
          if (data.server2.areaList[0]!=='0'){
              areaCode=data.server2.areaList[0];
          }
      }
      if (data.treeType >= 2){
          initAreaSelectBySelectedCode("province", "city", "district", data.regionCode);
      }
      //warehouseOperator.addLines(null);

      /*$("#addOrUpdateForm input[name='channelCode']").on('input propertychange',function () {
       var storeCode=$("#addOrUpdateForm input[name='channelCode']").val().trim();
       $("#addOrUpdateForm input[name='priceSource']").val(storeCode);
       });*/
    });

    /*$('#province option').filter(function () {
        return $(this).html() == areaData.province; }).attr("selected", true);
    $('#province').trigger("change");
    $('#city option').filter(function () {
        return $(this).html() == areaData.city; }).attr("selected", true);

    $('#city').trigger("change");
    $('#regionCode option').filter(function () {
        return $(this).html() == areaData.district; }).attr("selected", true);
    });*/

  }

  function updateTreeNode(treeNode, data) {
    for (var prop in data) {
      var value = data[prop];
      if (value) {
        treeNode[prop] = value;
      }
    }
    treeObj.updateNode(treeNode);
  }

  function clearAll() {
    $(".revisable", "#category-details").val("");
    $("input[name='categoryStatus']").attr("checked", false);
    refreshTree($("#channelSelect").val());
  }

  $(document).ready(function () {
    $("#search_channel").on("input", function (event) {
      searchNode(event.target.value);
    });

    $("#addNextChannelBtn").hide();
    $("#importChildChannelBtn").hide();

    $("#addTopChannelBtn").on("click", function () {
      var data = {};
      data.operationType = 0;
      data.warehouseCode = '';
      data.defaultPriceType = 1;
      data.treeType=0;
      data.chequesType=0;
      data.distributionType=0;
      data.channelType=0;
      data.isCheckStock='Y';
      data.isRebateRefund='N';
      showChannelDetail(data);
    });
    $("#addNextChannelBtn").on("click", function () {
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length <= 0) {
        layer.msg("请选中一个渠道");
        return;
      }
      var topChannelCode = $("#channelSelect").val();
	
      var data = nodes[0];
      if (data.treeType === 3) {
	        $X("/boss/channelService", "getChannelByChannelCode").callx({
	          channelCode: data.channelCode,
	          onResult: function (result) {
	            // if (result && result.warehouseCode) {
	            //   layer.alert("该渠道下面有关联仓库，不能增加下一级渠道")
	            // } else {
	              var newData = {parentCode: data.channelCode, parentChannelName: data.name,treeType:2};
	              newData.topChannelCode = topChannelCode;
	              newData.operationType = 0;
	              newData.warehouseCode = '';
	              showChannelDetail(newData);
	            // }
              layer.closeAll('loading');
	          },
	          onError: function (error) {
	            onError(error);
	          }
	        });
      } else {
        var newData = {parentCode: data.channelCode, parentChannelName: data.name,treeType:2};
        newData.topChannelCode = topChannelCode;
        newData.operationType = 0;
        newData.warehouseCode = '';
        showChannelDetail(newData);
      }
    });

    refreshTopChannel(function () {
      var selectCode = $("#channelSelect").val();
      //调用类目接口展示
      refreshTree(selectCode);
    });

    $("#importChildChannelBtn").on("click", function () {  //导入子渠道按钮

    });

  });

  function refreshTopChannel(callback) {
    $X("/boss/channelService", "listAllTopChannel").callx({
      onResult: function (result) {
        var html = '';
        if (result && result.length > 0) {
          for (var i = 0, length = result.length; i < length; i++) {
            var item = result[i];
            html += '<option value="' + item.channelCode + '">' + item.name + '</option>';
            topChannelData[item.channelCode] = item;
          }
        } else {
          //如果没有任务数据，则返回
          return ;
        }
        $("#channelSelect").html(html);
        $("#channelSelect").select2({
          allowClear: true,
          escapeMarkup: function (m) {
            return m;
          }
        });
        callback();
      },
      onError: function (error) {
        //onError(error);
      }
    }, 10000);
  }

  function searchNode(value) {
    updateNodes(null, false);
    if (value.trim().length > 0) {
      var nodeList = treeObj.getNodesByParamFuzzy("name", value) || [];

      if (nodeList && nodeList.length > 0) {
        treeObj.expandAll(false);
        treeObj.expandNode(treeObj.getNodes()[0], true, false, true);
        updateNodes(nodeList, true);
      }
    }

  }

  function updateNodes(nodeList, highlight) {
    if (!highlight) {
      updateByParent(treeObj.getNodes(), highlight);
    } else {
      for (var i = 0, len = nodeList.length; i < len; i++) {
        nodeList[i].highlight = highlight;
        treeObj.updateNode(nodeList[i]);
        if (highlight) {
          expandNode(nodeList[i], true);
        }

      }
    }
  }

  function updateByParent(nodeList, highlight) {
    if (nodeList && nodeList.length > 0) {
      for (var i = 0, len = nodeList.length; i < len; i++) {
        var node = nodeList[i];
        node.highlight = highlight;
        treeObj.updateNode(node);
        if (node.children && node.children.length > 0) {
          updateByParent(node.children, highlight);
        }
      }
    }
  }

  function expandNode(treeNode, isExpend) {
    if (treeNode) {
      var parentNode = treeNode.getParentNode();
      if (parentNode != null) {
        treeObj.expandNode(parentNode, true, false, true);
        expandNode(parentNode, isExpend);
      }
    }

  }

  function getFontCss(treeId, treeNode) {
    return (!!treeNode.highlight) ? {color: "#A60000", "font-weight": "bold"} : {
      color: "#333",
      "font-weight": "normal"
    };
  }

  function getUpdateData(updateAllData, data) {
    var updateData=null;
    if (updateAllData.id != undefined && updateAllData.id != '') {  //判断是否修改
        //主属性是否一致
      if (updateAllData.id === data.id) {
           updateData = {};
          if (updateAllData.channelStatus && updateAllData.channelStatus!=data.channelStatus){
              updateData.channelStatus=updateAllData.channelStatus;
          }
          if (updateAllData.channelType && updateAllData.channelType!=data.channelType){
              updateData.channelType=updateAllData.channelType;
          }
          if (updateAllData.channelName && updateAllData.channelName != data.name){
              updateData.name=updateAllData.channelName;
          }
          if (updateAllData.priceSource && updateAllData.priceSource != data.priceSource){
              updateData.priceSource=updateAllData.priceSource;
          }
          if (updateAllData.channelPayeeType && updateAllData.channelPayeeType != data.channelPayeeType){
              updateData.channelPayeeType=updateAllData.channelPayeeType;
          }
          if (updateAllData.isCheckStock && updateAllData.isCheckStock != data.isCheckStock){
              updateData.isCheckStock=updateAllData.isCheckStock;
          }
         /* if (updateAllData.warehouseCode && updateAllData.warehouseCode != data.warehouseCode){
              updateData.warehouseCode=updateAllData.warehouseCode;
          }*/
          if (updateAllData.remark && updateAllData.remark != data.remark){
              updateData.remark = updateAllData.remark;
          }

          //详细
          if (updateAllData.serviceTime != data.serviceTime){
              updateData.serviceTime=updateAllData.serviceTime;
          }
          if (updateAllData.stocksProportion && updateAllData.stocksProportion != data.stocksProportion){
              updateData.stocksProportion=updateAllData.stocksProportion;
          }
          if (updateAllData.longitude){
              updateData.longitude = updateAllData.longitude;
          }
          if (updateAllData.latitude){
              updateData.latitude = updateAllData.latitude;
          }
          if (updateAllData.address){
              updateData.address = updateAllData.address;
          }
          if (updateAllData.hasGoods){
              updateData.hasGoods = updateAllData.hasGoods;
          }

          if(updateAllData.name) {
            updateData.name = updateAllData.name;
          }

          updateData.cashOnDelivery = updateAllData.cashOnDelivery1;
          updateData.customerPickUp = updateAllData.customerPickUp1;
          var channelServerList=updateAllData.channelServerList;
          updateData.channelServerList=channelServerList;
          updateData.id = updateAllData.id;
          updateData.hasLeaf = data.hasLeaf;
          
          var region = {};
          region.topChannelCode = updateAllData.topChannelCode;
          region.channelCode = updateAllData.channelCode;
          if(updateAllData.district) {
            region.regionCode = updateAllData.district;  
          } else if(updateAllData.city) {
            region.regionCode = updateAllData.city;  
          } else if(updateAllData.province) {
            region.regionCode = updateAllData.province;
          }
          
          updateData.channelRegion = region;
      }
    }
    return updateData;
  }



  function openWarehouse(btn) {
    var selectDatas = [];
    var $btn = $(btn);
//        var $rowDiv=$btn;
    openWarehouseSelect(selectDatas, function (selectData) {
        if(selectData != null) {
            $btn.parent().parent().find("input[name='warehouseCode']")
                .val(selectData[0].warehouseCode)
          $btn.parent().parent().find("input[name='warehouseCodeAndName']")
          .val(selectData[0].warehouseCode + '-' + selectData[0].name)
          .attr('data_warehouseCode', selectData[0].warehouseCode);
          $(".autoClass").removeClass("hidden");
        } else {
            $btn.parent().parent().find("input[name='warehouseCode']")
                .val('')
            $btn.parent().parent().find("input[name='warehouseCodeAndName']")
                .val('选择仓库')
                .attr('data_warehouseCode', '');
            $(".autoClass").removeClass("hidden");
        }
    });
  }

  function validateForm(data) {
    var topChannelCode = $("#channelSelect").val();
    var channelCodeRegex = /^[a-zA-Z0-9_]{1,40}$/;
    var jwreg = /^\d{1,3}\.\d{0,6}$/;
    var newChannelCode = data.channelCode;
    var longitude = data.longitude;
    var latitude = data.latitude;
    if (data.name.trim().length === 0) {
      layer.tips('渠道名称不能为空', '#addOrUpdateForm input[name="name"]', {
        tips: [2, '#ff4400']
      });
      return false;
    } else if ($.trim(data.name).length > 20) {
      layer.tips('渠道名称不能超过20个汉字', '#addOrUpdateForm input[name="name"]', {
        tips: [2, '#ff4400']
      });
      return false;
    } else if ($.trim(data.channelCode).length === 0) {
      layer.tips('渠道编号不能为空', '#addOrUpdateForm input[name="channelCode"]', {
        tips: [2, '#ff4400']
      });
      return false;
    } else if (!newChannelCode.match(channelCodeRegex)) {
      layer.tips('渠道编号格式错误，1-40位字母或者数字', '#addOrUpdateForm input[name="channelCode"]', {
        tips: [2, '#ff4400']
      });
      return false;
    }  else if ($.trim(data.channelDesc).length > 100) {
      layer.tips('渠道说明不能超过100个字', '#addOrUpdateForm textarea[name="channelDesc"]', {
        tips: [2, '#ff4400']
      });
      return false;
    } else if (longitude && !longitude.match(jwreg)) {
      layer.tips('渠道经度不合法', '#addOrUpdateForm input[name="longitude"]', {
        tips: [2, '#ff4400']
      });
      return false;
    }  else if (latitude && !latitude.match(jwreg)) {
      layer.tips('渠道纬度不合法', '#addOrUpdateForm input[name="latitude"]', {
        tips: [2, '#ff4400']
      });
      return false;
    } 
    return true;
  }

  /*导入渠道*/
  function channelImport() {
    var innerHtml = $.openx.innerHtml('channelImportDiv');
      var selectChannelInfo= $('#addOrUpdateForm input[name="selectChannelInfo"]').val();

      if (selectChannelInfo && selectChannelInfo.length>0){
          var selectChannel=JSON.parse(selectChannelInfo);
          var data={
              parentChannelName:selectChannel.channelName,
              parentChannelCode:selectChannel.channelCode,
              parentId:selectChannel.id,
              topChannelCode:$('#channelSelect').val()
          };
          var channelLayer = laytpl(innerHtml).render(data, function (html) {
              //TODO channelImportDiv
              $.openx.openLayer(['400px', '400px'], '子渠道导入', html, false);
              $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",});
              initAreaSelectBySelectedCode("batchProvince", "batchCity", "batchDistrict",null);
          })

      }else{
          layer.msg('没有选择父渠道');
      }
  }

  function importExcel() {
    loadFileDataToBase64String('importChannelFile', function (excel) {
        var batchData = $.openx.getJsonObj("batchInportChannelForm");
        var channelServerList=[];
        var channel = {};
        if(batchData.cashOnDelivery1) {
          channel.cashOnDelivery = batchData.cashOnDelivery1;
        }
        if(batchData.customerPickUp1) {
          channel.customerPickUp = batchData.customerPickUp1;
        }

        if(batchData.parentChannelCode) {
          channel.parentCode = batchData.parentChannelCode;
        }

        if(batchData.serviceTime) {
          channel.serviceTime = batchData.serviceTime;
        }
        if(batchData.topChannelCode) {
          channel.topChannelCode = batchData.topChannelCode;
        }
        channel.serviceMode = batchData.serviceMode;
        channel.hasGoods = batchData.hasGoods;
        var channelRegion = {};
        var district = $('#batchDistrict').val();
        var city = $('#batchCity').val();
        var province = $('#batchProvince').val();
        if(district) {
          channelRegion.regionCode = district;
        } else if(city) {
          channelRegion.regionCode = city;
        } else if(province) {
          channelRegion.regionCode = province;
        }
        
        channel.channelRegion = channelRegion;

        /*
        if (batchData.serviceType0){
            channelServerList.push({serviceType:0})
        }
        if (batchData.serviceType1){
            channelServerList.push({serviceType:1,cashOnDelivery:batchData.cashOnDelivery1,customerPickUp:batchData.customerPickUp1})
        }

        if (batchData.serviceType2){
            var areaCode = getSelectedCode("batchProvince")||'0';
            channelServerList.push({serviceType:2,cashOnDelivery:batchData.cashOnDelivery2,areaList:[areaCode]})
        }

        batchData.channelServerList = channelServerList;
      */
      $X("/boss/channelService", "importExcel").callx({
        base64Str: excel,
        channel: channel,
        onResult: function (data) {
            layer.closeAll('loading');
            if(data && data.length > 0) {
                layer.alert(data + '');
            } else {
                layer.alert("已加入导入队列!!!", function() {
                    layer.closeAll();
                });
            }
        },
        onError: function (error) {
          var res = JSON.parse(error);
          if ($(".layui-layer-title").text() != "") {
            layer.msg(res.message)
          }
        }
      }, 3600 * 1000);
    });
  }

  function loadFileDataToBase64String(fileName, callback) {
    var file = document.getElementById(fileName).files[0];
    if (!file) {
        layer.msg("请选择文件");
      return -1;
    }

    if (file.name.lastIndexOf('.')===-1){
        layer.msg('上传的文件路径不正确');
    }else{
        var extName = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();//（把路径中的所有字母全部转换为小写）
        var AllImgExt=".xls|.xlsx|";
        if(AllImgExt.indexOf(extName+"|")==-1) {
            layer.msg("请上传excel");
            return false;
        }
        var size=file.size/1024/1024;
        if(size>5){
            layer.msg("上传的excel小于5M");
            return false;
        }
    }


    //读取文件
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      var result = this.result.split('base64,')[1];
      callback(result);
    }
  }

  /*var warehouseOperator = {
    addLines: function (datas) {
      console.log("-----");

      var $rows = $(".warehouse_row");
      if ($rows.length >= 3) {
        layer.msg('绑定的仓库数量不能查过3')
        return;
      }

      if (!datas) {
        var mainWarehouse = 1;
        if ($rows.length >= 1) {
          mainWarehouse = 0;
        }
        datas = [{mainWarehouse: mainWarehouse, stocksType: 1, stocksProportion: 0}]
      }
      var innerHTML = $("#warehouseLinesTemplate").html();
      laytpl(innerHTML).render(datas, function (html) {
        $(html).appendTo("#warehouseDiv");
        $("ul.dropdown-menu li a").on('click', function () {
          var text = $(this).text();
          var code = $(this).attr("code");
//                    var dataType=$(this).attr("data_type");
          var $btnNode = $(this).parent().parent().prev();
          if (code === '1') {
            if (!$btnNode.hasClass("btn-primary")) {
              $btnNode.removeClass("btn-default").addClass("btn-primary");
            }
          } else {
            $btnNode.removeClass("btn-primary").addClass("btn-default");
          }
          $btnNode.html(text + '<span class="caret"></span>').attr('code', code);
        });

      });
    },
    delLines: function (btn) {
      var $rows = $(".warehouse_row");
      if ($rows.length === 1) {
        layer.msg('清空了选择的仓库信息')
        return;
      }
      $(btn).parent().parent().remove();
    }
  }*/


   /*导入渠道*/
   function batchChannelUpdte() {
    var innerHtml = $.openx.innerHtml('batchUpdateChannelTemplate');
      var data = {};
      var channelLayer = laytpl(innerHtml).render(data, function (html) {
          $.openx.openLayer(["550","400"], '批量修改', html, false);
          $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",});
      });
      deliveryTime();
  }

function deliveryTime(){
    var h=0, m=0;
        var inp_h = document.getElementById("inp_h");
        var end_h = document.getElementById("end_h");

        console.log(inp_h.options)
        //清空小时和分钟已有的选项
        for (var i=0; i<inp_h.options.length; )
        {
            inp_h.remove(inp_h.options[i]);
            end_h.remove(end_h.options[i]);
        }

        var nopt1 = document.createElement("option");
        nopt1.text = "不变更";
        nopt1.value = "";
        inp_h.add(nopt1);

        var nopt2 = document.createElement("option");
        nopt2.text = "不变更";
        nopt2.value = "";
        end_h.add(nopt2);

        for (h; h<24; h++)
        {
            var opt = document.createElement("option");
            opt.text = h<10 ? '0'+h +':00' : h +':00';
            opt.value = h<10 ? '0'+h +':00' : h +':00';
            inp_h.add(opt);
            var opt2 = document.createElement("option");
            opt2.text = h<10 ? '0'+h +':30' : h +':30';
            opt2.value = h<10 ? '0'+h +':30' : h +':30';
            inp_h.add(opt2);
            var opt3 = document.createElement("option");
            opt3.text = h<10 ? '0'+h +':00' : h +':00';
            opt3.value = h<10 ? '0'+h +':00' : h +':00';
            end_h.add(opt3);
            var opt4 = document.createElement("option");
            opt4.text = h<10 ? '0'+h +':30' : h +':30';
            opt4.value = h<10 ? '0'+h +':30' : h +':30';
            end_h.add(opt4);
        }   

        var options = document.getElementById('inp_h').children;
        options[0].selected=true;
        var options = document.getElementById('end_h').children;
        options[0].selected=true;
}

function importBatchExcel() {
  loadFileDataToBase64String('importBatchChannelFile', function (excel) {
    $X("/boss/channelService", "parseBatchUpdateExcel").callx({
      base64Str: excel,
      onResult: function (data) {
          layer.closeAll('loading');
          if(data) {
            $('#batchUpdateChannel').text(data);
          } else {
            layer.msg("导入的渠道数据不能为空");
          }
      },
      onError: function (error) {
        var res = JSON.parse(error);
        if ($(".layui-layer-title").text() != "") {
          layer.msg(res.message)
        }
      }
    }, 3600 * 1000);
  });
}

function saveBatchUpdate() {
  var data = {};
  var startTime = $('#inp_h').val();
  var endTime = $('#end_h').val();
  if(startTime != '' && endTime == '') {
    layer.msg('请选择营业结束时间');
    return ;
  }

  if(startTime == '' && endTime != '') {
    layer.msg('请选择营业开始时间');
    return ;
  }
  if(startTime && endTime) {
    data.serviceTime = startTime + '-' + endTime;
  }

  var channelState = $("#batchUpdateChannelForm input[name='updateChannelStatus']:checked").val();
  data.channelStatus = channelState;

  var remark = $('#batchUpdateRemark').val();
  if(remark && remark.length > 200) {
    layer.msg('渠道说明不能超过100个中文字符');
    return ;
  }
  data.remark = remark;

  var batchUpdateChannel = $('#batchUpdateChannel').val();
  data.channelCode = batchUpdateChannel;

  if(!data.channelCode) {
    layer.msg("请上传渠道");
    return ;
  }

  if(!data.serviceTime && !data.channelStatus && !data.remark) {
    layer.msg("营业时间、营业状态、渠道说明请至少选一个");
    return ;
  }

  $X("/boss/channelService", "batchUpdateChannel").callx({
    channel: data,
    onResult: function (data) {
        layer.closeAll('loading');
        layer.alert("成功更新" + data + '家门店', function() {
          layer.closeAll();
      });
    },
    onError: function (error) {
      var res = JSON.parse(error);
      if ($(".layui-layer-title").text() != "") {
        layer.msg(res.message)
      }
    }
  }, 3600 * 1000);
}